<?php

namespace App\Api;

use App\Exports\RecordsExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreRecordRequest;
use App\Http\Requests\UpdateRecordRequest;
use App\Models\Record;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RecordController extends Controller
{
    public function index(Request $request)
    {
        $username = $request->query("user_name");
        $user_id = null;
//        解释$user_id为null有2种情况，1是通过user_name搜索，但是没有搜索到，2是本身record模型中的user被删除了，导致没有user_id
        if (!is_null($username)) {
            $user = User::where("name", "=", $username)->first();
            if ($user) {
                $user_id = $user->id;
            }
        }
        //判断当前用户是否为某一个部门的管理员
        $depIds = Auth::user()->departments()->get()->pluck("id")->toArray();

        $count = Record::exactSearchField($request->all())->where("user_id", "=", $user_id)->count();
        if ($username != "" && $count == 0) {
            return $this->success("", ["data" => [], "count" => $count]);
        }
        if (Auth::user()->isMaster()) {
//            超管
            $records = Record::exactSearchField($request->all())->when(!is_null($user_id), function ($query) use ($user_id) {
                return $query->where("user_id", "=", $user_id);
            });
            //添加搜索日志，判断如果data中的key除了page之外，其他的都是搜索字段，value是搜索内容
            if (!is_null($request->video_id) || !is_null($request->wechat_id) || !is_null($request->user_name)) {
                $search_content = 'video_id:' . $request->video_id . ',' . 'wechat_id:' . $request->wechat_id . ',' . 'user_name:' . $request->user_name;
                Auth::user()->logs()->create(['type' => "search", 'content' => $search_content]);
            }
            if($username==""&&$request->video_id==""&&$request->wechat_id==""){
                return $this->success("", ["data" => $records->paginate(10), "count" => 0]);
            }else{
                return $this->success("", ["data" => $records->paginate(10), "count" => $count]);
            }
        } elseif (count($depIds) > 0) {
//            部门管理员
            $depId = $depIds[0];
            $userIds = User::where("department_id", "=", $depId)->get()->pluck("id")->toArray();
            if (!is_null($request->video_id) || !is_null($request->wechat_id) || !is_null($request->user_name)) {
                $search_content = 'video_id:' . $request->video_id . ',' . 'wechat_id:' . $request->wechat_id . ',' . 'user_name:' . $request->user_name;
                Auth::user()->logs()->create(['type' => "search", 'content' => $search_content]);
            }
            $records = Record::exactSearchField($request->all())->whereIn("user_id", $userIds)->when($user_id, function ($query) use ($user_id) {
                return $query->where("user_id", "=", $user_id);
            });
            if($username==""&&$request->video_id==""&&$request->wechat_id==""){
                return $this->success("", ["data" => $records->paginate(10), "count" => 0]);
            }else{
                return $this->success("", ["data" => $records->paginate(10), "count" => $count]);
            }
        } else {
//            普通用户
            if (!is_null($request->video_id) || !is_null($request->wechat_id) || !is_null($request->user_name)) {
                $search_content = 'video_id:' . $request->video_id . ',' . 'wechat_id:' . $request->wechat_id . ',' . 'user_name:' . $request->user_name;
                Auth::user()->logs()->create(['type' => "search", 'content' => $search_content]);
            }
            $records = Record::exactSearchField($request->all())->where("user_id", "=", Auth::id())->when($user_id, function ($query) use ($user_id) {
                return $query->where("user_id", "=", $user_id);
            });
            if($username==""&&$request->video_id==""&&$request->wechat_id==""){
                return $this->success("", ["data" => $records->paginate(10), "count" => 0]);
            }else{
                return $this->success("", ["data" => $records->paginate(10), "count" => $count]);
            }
        }
    }

    public function store(StoreRecordRequest $request)
    {
        Record::create(['user_id' => Auth::id(), "expired_at" => now()->addDays(35)] + $request->input());
//        记录日志
//        Log::create(["user_id" => Auth::id(), "type" => "record", "content" => "添加了一条记录"]);
        return $this->success("添加成功");
    }

    /**
     * Display the specified resource.
     */
    public function show(Record $record)
    {
        return $this->success("获取成功", $record);
    }


    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateRecordRequest $request, Record $record)
    {
//       @yuanhao 当更新的时候，第一判断是否为自己的记录，第二判断是否为管理员
        if ($record->user_id != Auth::id() && !Auth::user()->isMaster()) {
            return $this->error("无权修改");
        }
        if ($record->order_img == $request->order_img) {
            //图片未做修改时，不允许修改
            $record->update($request->input());
            return $this->success("修改成功");
        } else {

//      @yuanhao  只有提交的截图发生变化时，过期时间为当前时间向后推迟35天，即为35天后过期，重新计算开始时间
            $record->update(["start_at" => now(), "expired_at" => now()->addDays(35)] + $request->input());
            return $this->success("修改成功");
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Record $record)
    {
        $record->delete();
        return $this->success("删除成功");
    }

//    按员工统计，获取周排行

    public function weekrank(Request $request)
    {
//        carbon获取本周，然后查询本周的record数据，根据用户关联查询records，数量由多到少排序，取前十
        $records = Record::whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
            ->withCount('user')->orderBy('user_count', 'desc')->take(10)->get();
        return $this->success("获取成功", $records);
    }

//按员工统计，获取月排行

    public function monthrank(Request $request)
    {
        $month = $request->query("month", Carbon::now()->month);
//        carbon获取本月，然后查询本周的record数据，根据用户关联查询records，数量由多到少排序，取前十
        $records = Record::whereMonth('created_at', $month)
            ->withCount('user')->orderBy('user_count', 'desc')->take(10)->get();
        return $this->success("获取成功", $records);

    }

//按员工统计，获取日排行
    public function dayrank(Request $request)
    {
        $day = $request->query("day", Carbon::now()->day);
//        carbon获取当天，然后查询本周的record数据，根据用户关联查询records，数量由多到少排序，取前十
        $records = Record::whereDay('created_at', $day)
            ->withCount('user')->orderBy('user_count', 'desc')->take(10)->get();
        return $this->success("获取成功", $records);
    }

    public function export(Request $request)
    {
        $user_id = $request->user_id;
        return $user_id ? $this->success("获取成功", new RecordsExport($user_id)) : $this->success("获取成功", new RecordsExport());
    }

    public function check(Request $request)
    {
//        判断是否存在
        $record = Record::where("wechat_id", "=", $request->wechat_id)->first();
        if (!$record) {
            return ["is_exist" => false];
        } else {
            return ["is_exist" => true];
        }
    }

    public function trashed(Request $request)
    {
        if (Auth::user()->isMaster()) {
            $records = Record::exactSearchField($request->all())->onlyTrashed();
            return $this->success("", $records->whereNotNull('deleted_at')->Orderby("start_at", "desc")->paginate(10));
        } else {
            $records = Record::exactSearchField($request->all())->where("user_id", "=", Auth::id());
            return $this->success("", $records->whereNotNull('deleted_at')->Orderby("start_at", "desc")->paginate(10));
        }
    }
}
